package com.nowcoder.community.controller.interceptor;

import com.nowcoder.community.annotation.LoginRequested;
import com.nowcoder.community.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Component
public class LoginRequestedInterceptor implements HandlerInterceptor {
    @Autowired
    private HostHolder hostHolder;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // HandlerMethod是springMVC提供的类型，方法类型
        // 目前只拦截设置头像修改
        if (handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            LoginRequested loginRequested = method.getAnnotation(LoginRequested.class);
            if (loginRequested != null && hostHolder.getUser() == null){
                // request.getContextPath()：项目路径
                response.sendRedirect(request.getContextPath() + "/login");
                // 终止请求
                return false;
            }
        }
        return true;
    }

}
